package com.pro01.apirednote.service.serviceImpl;

import com.pro01.apirednote.mapper.ContentLikeMapper;
import com.pro01.apirednote.mapper.ContentMapper;
import com.pro01.apirednote.pojo.Result;
import com.pro01.apirednote.pojo.ContentLike;
import com.pro01.apirednote.service.ContentLikeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ContentLikeServiceImpl implements ContentLikeService {

    private final ContentLikeMapper likeMapper;

    private final ContentMapper contentMapper;

    // 点赞/取消点赞
    @Override
    public Result<Boolean> toggleLike(Long userId, Long contentId) {
        ContentLike like = likeMapper.findByUserIdAndContentId(userId, contentId);
        if (like == null) {
            likeMapper.insert(new ContentLike() {{
                setUserId(userId);
                setContentId(contentId);
            }});
            likeMapper.incrementLikeCount(contentId); // 👍 点赞 +1
            return Result.success(true);
        } else if (Boolean.TRUE.equals(like.getIsDeleted())) {
            likeMapper.restore(userId, contentId);
            likeMapper.incrementLikeCount(contentId); // 👍 点赞 +1
            return Result.success(true);
        } else {
            likeMapper.softDelete(userId, contentId);
            likeMapper.decrementLikeCount(contentId); // 👎 点赞 -1
            return Result.success(false);
        }
    }

    // 用户是否点赞了当前帖子
    @Override
    public Result<Boolean> hasLiked(Long userId, Long contentId) {
        ContentLike like = likeMapper.findByUserIdAndContentId(userId, contentId);
        boolean hasLiked = like != null && Boolean.FALSE.equals(like.getIsDeleted());
        return Result.success(hasLiked);
    }

}